package com.example.cart_system.Filter;

import com.example.cart_system.jwt.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/**")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();

        if (url.contains("/login") || url.contains("/register")) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = request.getHeader("token");

        if (token == null || token.isEmpty()) {
            log.info("token is empty");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
        try {
            JwtUtil.parseToken(token);
        } catch (Exception e) {
            log.info("token is wrong");
        }
        log.info("token is right");
        filterChain.doFilter(request, response);
    }


}
